package com.hxzy.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.resp.R;
import com.hxzy.common.util.JwtTokenService;
import com.hxzy.common.util.PasswordLockUtil;
import com.hxzy.controller.anonymous.merchandiser.resp.MerchandiserProcessResp;
import com.hxzy.controller.front.merchandiser.req.EnterpriseInfoReq;
import com.hxzy.controller.front.merchandiser.req.EnterpriseReq;
import com.hxzy.controller.front.merchandiser.resp.EnterpriseResp;
import com.hxzy.controller.vue.login.req.AdminLoginReq;
import com.hxzy.controller.vue.login.resp.AdminLoginResp;
import com.hxzy.controller.vue.merchandiser.req.MerchandiserReq;
import com.hxzy.controller.vue.merchandiser.req.ProcessReq;
import com.hxzy.controller.vue.merchandiser.resp.MerchandiserResp;
import com.hxzy.entity.EnterpriseProcess;
import com.hxzy.entity.Merchandiser;
import com.hxzy.service.EnterpriseProcessService;
import com.hxzy.service.MerchandiserService;
import com.hxzy.mapper.MerchandiserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
* @author 11452
* @description 针对表【merchandiser(商家信息)】的数据库操作Service实现
* @createDate 2023-08-28 11:54:55
*/
@Service
public class MerchandiserServiceImpl extends ServiceImpl<MerchandiserMapper, Merchandiser>
    implements MerchandiserService{

    @Autowired
    private PasswordLockUtil  passwordLockUtil;

    @Autowired
    private EnterpriseProcessService enterpriseProcessService;


    @Override
    public AdminLoginResp login(AdminLoginReq req) {
        LambdaQueryWrapper<Merchandiser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchandiser::getLoginName,req.getAccount());
        queryWrapper.select(Merchandiser::getId,Merchandiser::getName,Merchandiser::getLoginPwd,Merchandiser::getStatus,Merchandiser::getPicture);

        Merchandiser merchandiser = super.baseMapper.selectOne(queryWrapper);

        if(Objects.isNull(merchandiser)){
            throw new ServiceException(AckCode.LOGIN_ACCOUNT_PASSWORD_ERROR);
        }

        String uniqueValue= JwtTokenService.MERCHANDISER+"-"+ merchandiser.getId();

        boolean pwdSuccess= BCrypt.checkpw(req.getPassword(), merchandiser.getLoginPwd());

        if(this.passwordLockUtil.isPasswordLock()){
            if(!this.passwordLockUtil.isAccountLocked(uniqueValue)){
                //密码错误
                if(!pwdSuccess){
                    //把密码错误次数更新,如果超过3次，一定抛出异常,如果没有超过就不会抛出异常
                    this.passwordLockUtil.logFailedLoginAttempt(uniqueValue);
                }
            }
            //如果密码正确的，就要删除redisKey
            this.passwordLockUtil.unlockAccount(uniqueValue);
        }else {
            //没有开启密码锁的服务
            if(!pwdSuccess) {
                throw new ServiceException(AckCode.LOGIN_ACCOUNT_PASSWORD_ERROR);
            }
        }

        //账号未审核
        if(merchandiser.getStatus().equals("0")){
            throw new ServiceException(AckCode.MERCHANDISER_ACCOUNT_NOT_VERIFIED);
        }else if(merchandiser.getStatus().equals("2")){
            throw new ServiceException(AckCode.MERCHANDISER_ACCOUNT_VERIFIED_FAILED);
        }

        //转换对象
        AdminLoginResp  loginResp=new AdminLoginResp();
        loginResp.setId(merchandiser.getId());
        loginResp.setName(merchandiser.getName());
        loginResp.setPermissions(Arrays.asList("merchandiser"));
        loginResp.setAvatar(merchandiser.getPicture());
        loginResp.setRoot("0");
        return loginResp;
    }

    /**
     * 根据手机查询信息和审核状态
     * @param phone
     * @return
     */
    @Override
    public MerchandiserProcessResp searchByPhone(String phone) {

        //商家信息
        Map<String,Object> merchandiserMap=baseMapper.searchByPhone(phone);
        if(Objects.isNull(merchandiserMap)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        long id= (long) merchandiserMap.get("id");

        //审核历史记录
        List<Map<String,Object>> processMap=this.enterpriseProcessService.searchByTenantId(id);
        //一行数据都没有,添加一笔待审核信息
        if(processMap.isEmpty()){
            //id,status,description, create_time
            Map<String,Object>   newMap=new HashMap<>();
            newMap.put("status","0");
            newMap.put("description","审核中，请耐心等待...");
            processMap.add(newMap);
        }

        //组装自定义对象
        MerchandiserProcessResp  resp=new MerchandiserProcessResp();
        resp.setMerchandiser(merchandiserMap);
        resp.setProcessList(processMap);
        return resp;
    }

    @Override
    public PageInfo<MerchandiserResp> search(MerchandiserReq req) {
        return PageHelper.startPage(req.getPage(),req.getSize())
                .doSelectPageInfo(()->{
                   List<MerchandiserResp> list=baseMapper.search(req);

                });
    }

    /**
     * 审核
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean process(ProcessReq req) {
        Merchandiser db = this.getById(req.getTenantId());
        if (Objects.isNull(db)) {
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }
        //更新状态
        db.setStatus(req.getStatus());
        this.updateById(db);
        //新增记录
        EnterpriseProcess   process=new EnterpriseProcess();
        process.setTenantId(req.getTenantId());
        process.setDescription(req.getDescription());
        process.setStatus(req.getStatus());
        this.enterpriseProcessService.save(process);

        return true;
    }

    @Override
    public PageInfo<EnterpriseResp> frontSearch(EnterpriseReq req) {
        return PageHelper.startPage(req.getPage(),req.getSize())
                .doSelectPageInfo(()->{
                    List<EnterpriseResp> resps=this.baseMapper.frontSearch(req);

                });
    }

    /**
     * 查询商家信息
     * @param req
     * @return
     */
    @Override
    public EnterpriseResp findbyId(EnterpriseInfoReq req) {
        return this.baseMapper.findById(req);
    }
}




